package com.lm.ddd.domain.model;

import lombok.Data;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Data
public class Order {
    private final String orderId;
    private final List<OrderItem> items;
    private BigDecimal totalPrice;
    private OrderStatus status;
    private final LocalDateTime createdAt;

    public Order(String orderId, List<OrderItem> items) {
        this.orderId = orderId;
        this.items = items;
        this.status = OrderStatus.CREATED;
        this.createdAt = LocalDateTime.now();
        calculateTotalPrice();
    }

    private void calculateTotalPrice() {
        this.totalPrice = items.stream()
                .map(OrderItem::calculatePrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    // 支付订单
    public void pay() {
        if (this.status != OrderStatus.CREATED) {
            throw new IllegalStateException("订单状态错误，无法支付");
        }
        this.status = OrderStatus.PAID;
    }

    // 发货
    public void ship() {
        if (this.status != OrderStatus.PAID) {
            throw new IllegalStateException("订单未支付，无法发货");
        }
        this.status = OrderStatus.SHIPPED;
    }

    // getter 略

    @Override
    public String toString() {
        return "Order{" +
                "orderId='" + orderId + '\'' +
                ", totalPrice=" + totalPrice +
                ", status=" + status +
                ", createdAt=" + createdAt +
                '}';
    }
}